package com.easyjava.builder;

import com.easyjava.bean.Constants;
import com.easyjava.bean.FieldInfo;
import com.easyjava.bean.TableInfo;
import com.easyjava.utils.MyStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Locale;

/**
 * @Author: 小闹心
 * @Description: 创建枚举类
 * @DateTime: 2024/11/21 14:40
 **/
public class BuildEnum {
    public static final Logger logger = LoggerFactory.getLogger(BuildEnum.class);
    public static void execute(TableInfo tableInfo){
        if (tableInfo.getFieldEnumList().isEmpty()){
            return;
        }
        for(FieldInfo fieldInfo : tableInfo.getFieldEnumList()){
            if(Constants.CREATED_ENUMS.contains(MyStringUtils.lowerCaseFirstLetter(fieldInfo.getPropertyName()))){
                continue;
            }
            String upperPropertyName = MyStringUtils.upperCaseFirstLetter(fieldInfo.getPropertyName());
            String fileName = upperPropertyName + "Enum";
            File folder = new File(Constants.PATH_ENUMS);
            if(!folder.exists()){
                folder.mkdirs();
            }
            File javaFile = new File(folder,fileName + ".java");
            OutputStream out = null;
            OutputStreamWriter outWriter = null;
            BufferedWriter bw = null;
            try{
                out = new FileOutputStream(javaFile);
                outWriter = new OutputStreamWriter(out, StandardCharsets.UTF_8);
                bw = new BufferedWriter(outWriter);
                bw.write("package " + Constants.PACKAGE_ENUMS + ";");
                bw.newLine();
                bw.newLine();
                bw.write("import com.fasterxml.jackson.annotation.JsonFormat;");
                bw.newLine();
                bw.newLine();
                BuildComment.createClassComment(bw,fileName + "枚举类");
                bw.write("@JsonFormat(shape = JsonFormat.Shape.OBJECT)");
                bw.newLine();
                bw.write("public enum " + fileName + " implements BaseEnum {");
                bw.newLine();
                bw.newLine();
                String comment = fieldInfo.getComment();
                String[] split = comment.split(" ", 2);
                String enumNames = "";
                if(split.length > 1){
                    enumNames = split[1];
                    comment = split[0];
                }else {
                    enumNames = split[0];
                }
                // 对枚举名称进行处理，携程枚举模式
                String[] names = enumNames.split(Constants.DB_COMMENT_ENUM_INTERVAL);
                String prefix = "Enum" + upperPropertyName;
                for(int i = 0;i < names.length;i++){
                    String[] codeAndStatus = getCodeAndStatus(names[i]);
                    if(codeAndStatus == null){
                        continue;
                    }
                    bw.write("\t" + prefix + i + "(" + codeAndStatus[0]  + ",\"" + codeAndStatus[1] + "\")" );
                    if(i < names.length - 1){
                        bw.write(",");
                    }else {
                        bw.write(";");
                    }
                    bw.newLine();
                }
                bw.write("\tInteger code;");
                bw.newLine();
                bw.write("\tString status;");
                bw.newLine();
                bw.write("\t" + fileName + "(Integer code, String status) {");
                bw.newLine();
                bw.write("\t\tthis.code = code;");
                bw.newLine();
                bw.write("\t\tthis.status = status;");
                bw.newLine();
                bw.write("\t}");
                bw.newLine();
                bw.write("\t@Override");
                bw.newLine();
                bw.write("\tpublic Integer getCode() {");
                bw.newLine();
                bw.write("\t\treturn code;");
                bw.newLine();
                bw.write("\t}");
                bw.newLine();
                bw.write("\t@Override");
                bw.newLine();
                bw.write("\tpublic String getStatus() {");
                bw.newLine();
                bw.write("\t\treturn status;");
                bw.newLine();
                bw.write("\t}");
                bw.newLine();
                bw.write("}");
                bw.newLine();
                bw.flush();
                Constants.CREATED_ENUMS.add(MyStringUtils.lowerCaseFirstLetter(fieldInfo.getPropertyName()));
            }catch (Exception e){
                logger.error("生成枚举类: {} 失败" ,fileName);
            }finally {
                if(bw != null){
                    try {
                        bw.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(outWriter != null){
                    try {
                        outWriter.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(out != null){
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    // 对枚举名称进行处理，携程枚举模式
    private static String[] getCodeAndStatus(String name){
        String[] res = new String[2];
        name = name.replaceAll(" ","");
        int mid = 0;
        for(int i = 0; i < name.length(); i++){
            char c = name.charAt(i);
            if(c >= '0' && c <= '9'){
                mid = i + 1;
            }else{
                break;
            }
        }
        res[0] = name.substring(0,mid);
        res[1] = name.substring(mid);
        if(res[0].isEmpty() && res[1].isEmpty()) return null;
        return res;
    }

}
